package com.darren.archive.dao.impl;

import com.darren.archive.dao.SysFunctionDao;
import com.darren.archive.entity.SysFunction;
import com.darren.framework.dao.impl.GenericDaoImpl;
import com.darren.framework.utils.StringUtils;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public class SysFunctionDaoImpl extends GenericDaoImpl<SysFunction, Long> implements SysFunctionDao {

    @Override
    public List<SysFunction> getAllEnableFunction() {
        Session session = sessionFactory.getCurrentSession();
        Query<SysFunction> query = session.createQuery("select f from SysFunction f  where f.enable = true and f.delete = false ", SysFunction.class);
        List<SysFunction> sysFunctionList = query.list();
        return sysFunctionList;
    }

    @Override
    public List<SysFunction> getEnableSysFunctionByUserId(Long userId) {
        Session session = sessionFactory.getCurrentSession();
        Query<SysFunction> query = session.createQuery("select f from SysFunction f inner join SysRoleFunction  as rf on f.id = rf.functionId inner join SysUserRole ur on rf.roleId = ur.roleId where f.enable = true and f.delete = false  and ur.userId =:userId ", SysFunction.class);
        query.setParameter("userId", userId);
        List<SysFunction> sysFunctionList = query.list();
        return sysFunctionList;
    }

    /**
     * 根据系统菜单名称，获取系统功能/菜单树型结构（包含启用 和  禁用的）
     *
     * @param functionName 系统菜单名称，用于模糊查询
     * @return
     */
    @Override
    public List<SysFunction> getAllByFunctionName(String functionName) {
        Session session = sessionFactory.getCurrentSession();
        String hSQL= "select f from SysFunction f  where  f.delete = false ";
        Query query = null;
        if(StringUtils.isEmpty(functionName)){
            query = session.createQuery(hSQL,SysFunction.class);
            return query.list();
        }else{
            hSQL= "select f from SysFunction f  where f.functionName like :functionName  and  f.delete = false ";
            query = session.createQuery(hSQL,SysFunction.class);
            query.setParameter("functionName", "%"+functionName+"%");
            return query.list();
        }
    }
}